package com.hy.service.impl;

import com.hy.entity.pojo.SysMenu;
import com.hy.entity.pojo.SysRole;
import com.hy.entity.pojo.SysUser;
import com.hy.mapper.SysRoleMapper;
import com.hy.mapper.SysUserMapper;
import com.hy.security.entity.SecurityUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

//自定义UserDetailsService实例对象，改用自己定义的。
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户查询用户权限列表
        Integer id=Integer.valueOf(username);
        SysUser sys_user = sysUserMapper.findSysUserByUsername(id);
        //判断
        if(sys_user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //RBAC基于角色的权限控制
       /* //根据用户id查询对应角色信息
        List<SysRole> roleList = sysRoleMapper.findSysRoleByUserId(sys_user.getId());
        //角色用Set来装，目的是去重，还有info对象中需要Set格式
        Set<String> roleSets = new HashSet<>();
        //获取角色ID
        List<Integer> role_ids = new ArrayList<>();
        for (SysRole role:roleList) {
            roleSets.add(role.getTitle());
            role_ids.add(role.getId());
        }*/
        //根据账户id查询对应的角色
        //根据对应的角色id查询对应权限

        //===============================================
        Set<String> sys_menuSets = new HashSet<>();
        SysMenu sysMenu=new SysMenu();
        sysMenu.setUrl("/hello");
        sys_menuSets.add(sysMenu.getUrl());
        /*List<SysMenu> sys_menus = sysRoleMapper.findMenuListByRoleId(sys_user.getRoleId());
        for (SysMenu sm:sys_menus) {
            sys_menuSets.add(sm.getTitle());
        }*/
        //将查询的账户与权限塞给SecurityUser对象
        SecurityUser securityUser = new SecurityUser();
/*        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sys_user,sysUser);*/
        //塞对象
        securityUser.setCurrentUserInfo(sys_user);
        //塞权限
        securityUser.setPermissionValueList(sys_menuSets);
        return securityUser;
    }
}
